<template>
  <div class="role-list-container">
    <!-- 页面标题、搜索框和添加按钮 -->
    <div class="page-header">
      <h2 style="font-weight: 700;">角色列表</h2>
      <div class="search-container">
        <el-input 
          v-model="searchQuery" 
          placeholder="请输入角色名称搜索" 
          clearable
          style="width: 300px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleAddRole" style="margin-left: 10px;">
          <el-icon><Plus /></el-icon> 添加角色
        </el-button>
      </div>
    </div>

    <!-- 角色表格 -->
    <el-table :data="roleList" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="roleName" label="角色" />
      <el-table-column prop="roleDesc" label="描述" />
      <el-table-column prop="createName" label="创建者">
        <template  #default="scope">管理者：{{ scope.row.createName }}</template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期">
        <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[2,5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 角色添加对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加角色"
      width="600px"
    >
      <el-form 
        ref="addFormRef"
        :model="addForm" 
        label-width="80px" 
        :rules="roleRules"
      >
        <el-form-item label="角色名称" prop="roleName" required>
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc" required>
          <el-input v-model="addForm.roleDesc" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="创建者" prop="createName"   required>
          <el-input v-model="addForm.createName" disabled placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="addForm.getPermissionIds">
            <el-checkbox 
              v-for="item in permissionOptions" 
              :key="item.permissionId" 
              :label="item.permissionId"
            >
              {{ item.permissionName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色编辑对话框（独立） -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑角色"
      width="600px"
    >
      <el-form 
        ref="editFormRef"
        :model="editForm" 
        label-width="80px" 
        :rules="roleRules"
      >
        <el-form-item label="角色名称" prop="roleName" required>
          <el-input v-model="editForm.roleName" placeholder="请输入角色名称"  />
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc" required>
          <el-input v-model="editForm.roleDesc" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="创建者" prop="createName"   required>
          <el-input v-model="editForm.createName" disabled placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="editForm.getPermissionIds">
            <el-checkbox 
              v-for="item in permissionOptions" 
              :key="item.permissionId" 
              :label="item.permissionId"
            >
              {{ item.permissionName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import httpInstance from '../../utils/http';

// 搜索和分页相关变量
const searchQuery = ref('');
const pageNo = ref(1);
const pageSize = ref(5);
const total = ref(0);
const roleList = ref([]);

// 添加角色对话框相关变量
const addDialogVisible = ref(false);
const addFormRef = ref(null);
const addForm = ref({
  roleName: '',
  roleDesc: '',
  createName: 'long',
  getPermissionIds: []
});

// 编辑角色对话框相关变量（独立）
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = ref({
  roleId: '',
  roleName: '',
  roleDesc: '',
  createName: '',
  getPermissionIds: []
});

// 表单验证规则
const roleRules = ref({
  roleName: [
    { required: true, message: '角色名称为必填项', trigger: 'blur' }
  ],
  roleDesc: [
    { required: true, message: '描述为必填项', trigger: 'blur' }
  ],  
});

// 权限列表
const permissionOptions = ref([]);


onMounted(() => {
  getRoleList();
  getPermissionList();
});

// 获取角色列表数据
const getRoleList = async () => { 
  try {
    const { data: res } = await httpInstance.post(`/eduservice/role/getRolePage/${pageNo.value}/${pageSize.value}`, { roleNameVo: searchQuery.value });
    roleList.value = res.data.list.list || [];
    total.value = res.data.list.total || 0;
      
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 获取权限列表数据
const getPermissionList = async () => { 
  try {
    const { data: res } = await httpInstance.get(`eduservice/permission/getPermissionAll`);
    console.log("权限接口返回数据：", res);
    permissionOptions.value = res.data.list || []; 
  } catch (error) {
    console.error('获取权限列表失败:', error);
    ElMessage.error('获取权限列表失败');
  }
};


// 搜索按钮点击事件
const handleSearch = () => {
  pageNo.value = 1;
  getRoleList();
};

// 分页大小改变事件
const handleSizeChange = (val) => {
  pageSize.value = val;
  pageNo.value = 1;
  getRoleList();
};

// 当前页码改变事件
const handleCurrentChange = (val) => {
  pageNo.value = val;
  getRoleList();
};

// 打开添加角色模态框操作
const handleAddRole = () => {
  const username = sessionStorage.getItem('username');
  addForm.value = { 
    roleName: '', 
    roleDesc: '', 
    createName: username || '未知创建者', 
    getPermissionIds: [] 
  };
  addDialogVisible.value = true;
};

// 编辑角色操作 - 打开编辑模态框并回显数据
const handleEdit = async (row) => {
  try {
    // 1. 获取角色详情数据（包含已选权限）
    const { data: res } = await httpInstance.get(`/eduservice/role/${row.roleId}`);
    
    // 2. 回显数据到编辑表单
    editForm.value = {
      roleId: row.roleId,
      roleName: res.data.role.roleName,
      roleDesc: res.data.role.roleDesc,
      createName: res.data.role.createName,
      getPermissionIds: res.data.role.getPermissionIds || [] // 回显已选择的权限
    };
    
    // 3. 显示编辑模态框
    editDialogVisible.value = true;
    console.log("回显数据：",res);  
  } catch (error) {
    console.error('获取角色详情失败:', error);
    ElMessage.error('获取角色详情失败，请重试');
  }
};

// 完善后的删除方法
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色【${row.roleName}】吗？删除后将同步移除该角色的所有权限关联`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await httpInstance.delete(`/eduservice/role/${row.roleId}`);
    ElMessage.success(`角色【${row.roleName}】删除成功`);
    getRoleList();
  } catch (error) {
    if (error.name === 'Cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除角色失败:', error);
      ElMessage.error('角色删除失败，请重试');
    }
  }
};

// 保存添加的角色
const handleAddSave = async () => {
  const valid = await addFormRef.value.validate();
  if (valid) {
    const requestData = {
      roleName: addForm.value.roleName,
      roleDesc: addForm.value.roleDesc,
      createName: addForm.value.createName,
      getPermissionIds: addForm.value.getPermissionIds
    };

    try {
      await httpInstance.post('/eduservice/role', requestData);
      ElMessage.success('角色添加成功');
      addDialogVisible.value = false;
      getRoleList();
    } catch (error) {
      console.error('保存角色失败:', error);
      ElMessage.error('角色添加失败，请重试');
    }
  } else {
    ElMessage.error('请填写必填项');
  }
};

// 保存编辑的角色
const handleEditSave = async () => {
  const valid = await editFormRef.value.validate();
  if (valid) {
    const requestData = {
      roleId: editForm.value.roleId,
      roleName: editForm.value.roleName,
      roleDesc: editForm.value.roleDesc,
      createName: editForm.value.createName,
      getPermissionIds: editForm.value.getPermissionIds
    };

    try {
      await httpInstance.put('/eduservice/role', requestData);
      ElMessage.success('角色编辑成功');
      editDialogVisible.value = false;
      getRoleList();
    } catch (error) {
      console.error('编辑角色失败:', error);
      ElMessage.error('角色编辑失败，请重试');
    }
  } else {
    ElMessage.error('请填写必填项');
  }
};

// 取消按钮操作（添加模态框）
const handleCancel = () => {
  addFormRef.value.resetFields();
  addDialogVisible.value = false;
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr || typeof dateStr !== 'string') return '';
  return dateStr.replace('T', ' ');
};
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.page-header h3 {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.search-container {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
